<template>
	<view class="chat-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-left">
				<text class="model-name">{{ botInfo?.name }}</text>
				<view class="model-status online"></view>
			</view>
			<view class="nav-right">
				<button class="function-btn" open-type="share">
					<uni-icons type="redo-filled" size="24" color="#3dc07c"></uni-icons>
				</button>

				<button class="function-btn" @tap="clearChat">
					<uni-icons type="trash" size="22" color="#666"></uni-icons>
				</button>
			</view>
		</view>

		<!-- 聊天内容区域 -->
		<scroll-view class="chat-content" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true"
			:show-scrollbar="false" :enable-passive="true" @scrolltoupper="loadMoreMessages" ref="chatScroll">
			<view class="welcome-card" v-if="messages?.length === 0">
				<image class="ai-avatar" :src="botInfo?.icon_url" mode="aspectFit"></image>
				<!-- {{ botInfo?.onboarding_info.prologue }} -->
				<text class="welcome-title">你好！我是{{ botInfo?.name }}</text>
				<text class="welcome-desc">{{botInfo?.description}}</text>
				<view class="suggestion-list">
					<view class="suggestion-item" v-for="(item, index) in suggestions" :key="index"
						@tap="selectSuggestion(item)">
						<uni-icons :type="item.icon" size="16" color="#3dc07c"></uni-icons>
						<text>{{ item.text }}</text>
					</view>
				</view>
			</view>

			<view class="message-list">
				<view v-for="(msg, index) in messages" :key="index"
					:class="['message-item', msg.type === 'user' ? 'message-right' : 'message-left']">
					<image class="avatar" :src="msg.type === 'user' ? userAvatar : botInfo?.icon_url" mode="aspectFill">
					</image>
					<view class="message-content" @longpress="handleLongPress(msg, index)">
						<text class="message-text"
							:class="{ 'user-text': msg.type === 'user' }">{{ msg.content }}</text>
						<view class="message-time">{{ msg.time }}</view>
					</view>

				</view>
			</view>

			<!-- 加载动画 -->
			<view class="loading-wrapper" v-if="isLoading">
				<view class="typing-indicator">
					<view class="dot"></view>
					<view class="dot"></view>
					<view class="dot"></view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部输入区域 -->
		<view class="input-area">
			<view class="input-wrapper" >
				<textarea class="input-box" v-model="inputMessage" :adjust-position="true" :show-confirm-bar="false" 
				:disabled="!AllowSendMessage" :auto-height="true" :cursor-spacing="20" :maxlength="-1" :placeholder="placeholder" @focus="handleFocus"
					@blur="handleBlur" @confirm="sendMessage"></textarea>
				<view class="send-btn" :class="{ 'active': inputMessage.trim() && AllowSendMessage,
    'disabled': !AllowSendMessage }" @tap="sendMessage">
					<uni-icons type="paperplane-filled" size="24" :color="inputMessage.trim() ? '#3dc07c' : '#999'">
					</uni-icons>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		chatApi,
		userApi
	} from '../../utils/api.js'
	import {
		BASE_URL
	} from '../../utils/request.js';
	import {
		jm
	} from '../../utils/tools.js'
	export default {
		data() {
			return {
				inputMessage: '',
				messages: [],
				isLoading: false,
				scrollTop: 0,
				userAvatar: '/static/logo.png',
				aiAvatar: '/static/uni.png',
				suggestions: [],
				botId: null,
				botName: null,
				botInfo: null,
				conversation_id: null,
				chat_id: null,
				eventSource: null,
				placeholder:'请输入您的问题...',
				userInfo:{},
			}
		},
		computed: {
			AllowSendMessage() {
				if(this.userInfo?.vip_type === 'free' && this.userInfo?.free_chat_number <= 0){
					this.placeholder = '您的免费次数已用完，请升级会员'
					return false;
				}
				return true;
			},
			 
		},
		onShow() {
			// let userInfo = uni.getStorageSync('userInfo');
			
			if (this.botId) {
				this.getAgent()
				this.getNewConversation()
			}
		},
		onLoad(options) {
			userApi.getUserInfo().then(res=>{
				this.userInfo = res.data;
				if(this.userInfo){
				this.userAvatar = this.userInfo?.wx_avatar || '/static/logo.png';
			}
			})
			uni.showShareMenu({
				menus: ['shareAppMessage', 'shareTimeline'],
				withShareTicket: true
			})
			// 从 options 对象中获取传递的参数
			this.botId = options.id;
			this.botName = options.name;
			if (this.botId) {
				this.getAgent()
				this.getNewConversation()
			} else {
				uni.navigateBack({
					delta: 1
				})
			}


		},
		onShareAppMessage: (op) => {
			return {
				title: this.botInfo.bot_name,
				imageUrl: this.botInfo.icon_url,
			}
		},
		methods: {
			async getAgent() {
				const agentRes = await chatApi.getAgentInfo({
					bot_id: this.botId
				})
				if (agentRes.success === false) {
					uni.showModal({
						title: '提示',
						content: '暂无该智能体',
						showCancel: false,
						success() {
							uni.navigateBack({
								delta: 1
							})
						}
					})
				}
				this.botInfo = agentRes.data
				this.suggestions = [];
				this.botInfo?.onboarding_info?.suggested_questions?.forEach((item) => {
					this.suggestions.push({
						text: item,
						icon: ['help', 'info', 'chat'][Math.floor(Math.random() * 3)]
					})
				})
			},
			async getNewConversation() {
				const conversationRes = await chatApi.getConversation({
					bot_id: this.botId
				})
				this.conversation_id = conversationRes.data.conversation_id;
				this.getAllHistory()
			},
			async getAllHistory() {
				if (this.conversation_id) {
					this.isLoading = true;
					const res = await chatApi.getHistory({
						conversation_id: this.conversation_id
					})
					res.data.data.sort((a, b) => a.updated_at - b.updated_at)
					// 确保数据结构一致
					const formattedMessages = res.data.data.map(message => ({
						type: message.role,
						content: message.content,
						time: this.formatTime(new Date(parseInt(message.updated_at) * 1000)),
						message_id: message.id
					}));
					this.messages = formattedMessages
					this.isLoading = false;
					this.$nextTick(() => {
						this.scrollToBottom();

					});
				}

			},
			sendNewMessage() {


				const aiMessage = {
					type: 'ai',
					content: '',
					time: this.formatTime(new Date())
				};
				
				const req = wx.request({
					url: BASE_URL + '/api/chat/createAndChat',
					method: 'POST',
					timeout: 150000,
					responseType: 'text',
					enableChunked: true,
					header: {
						'Authorization': uni.getStorageSync('token')
					},
					data: {
						conversation_id: this.conversation_id,
						bot_id: this.botId,
						content: this.inputMessage,
					},
					success: (res) => {
						console.log(res);
						if(res.data.success === false){
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							return;
						}
						
					},
				})
				req.onChunkReceived((response) => {
					const arrayBuffer = response.data;

					const uint8Array = new Uint8Array(arrayBuffer);
					// let text = uni.arrayBufferToBase64(uint8Array)

					let item = jm(uint8Array);
					// console.log(item);
					let json = item.split('\r\n');
					// console.log(json);
					json.forEach((item) => {
						// console.log(item);
						if (item) {
							let obj = JSON.parse(item);
							console.log(obj);
							if(obj.event === 'conversation.chat.created'){
								this.messages.push(aiMessage);
							}
							if (obj.event === 'conversation.message.delta') {
								if (this.messages.length >= 1) {
									this.messages[this.messages.length - 1].message_id = obj.data.id;
									this.messages[this.messages.length - 1].content += obj.data.content;
								}
								this.$nextTick(() => {
									this.scrollToBottom();
								});
							}
							if (obj.event === 'conversation.chat.created') {
								if (this.messages.length >= 2) {
									this.messages[this.messages.length - 2].message_id = obj.data.id;
								}

							}

							if (obj.event === 'done') {
								this.$nextTick(() => {
									this.scrollToBottom();
								});
								return;
							}
						}
					})
				})


			},
			sendMessage() {
				if (!this.inputMessage.trim() || this.isLoading) return;
				if (!this.AllowSendMessage && this.userInfo?.vip_type === 'free') {
      uni.showToast({
        title: '免费用户次数已用尽',
        icon: 'none'
      })
      return
    }

				// 添加用户消息
				const userMessage = {
					type: 'user',
					content: this.inputMessage,
					time: this.formatTime(new Date())
				};
				this.messages.push(userMessage);
				this.sendNewMessage()
				// 清空输入框
				this.inputMessage = '';

				// 等待消息渲染完成后滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom();
				});

			},
			selectSuggestion(suggestion) {
				this.inputMessage = suggestion.text;
				this.sendMessage();
			},
			async deleteConversion() {
				const res = await chatApi.delConversation({
					conversation_id: this.conversation_id
				})
			},
			clearChat() {
				uni.showModal({
					title: '提示',
					content: '确定要清空聊天记录吗？',
					success: (res) => {
						if (res.confirm) {
							this.deleteConversion()
							this.messages = [];
						}
					}
				});
			},

			handleLongPress(message, index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这条消息吗？',
					success: (res) => {
						if (res.confirm) {
							// 用户点击了确认按钮
							this.deleteMessage(index);
						} else if (res.cancel) {
							// 用户点击了取消按钮
							console.log('用户点击了取消');
						}
					}
				});
			},
			async deleteMessage(index) {
				
				// 从数据源中移除该消息
				const res = await chatApi.delMessages({
					conversation_id: this.conversation_id,
					message_id: this.messages[index].message_id
				})
				this.messages.splice(index, 1);
			},

			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			scrollToBottom() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.chat-content').boundingClientRect();
				query.select('.message-list').boundingClientRect();
				query.exec((res) => {
					if (res[0] && res[1]) {
						this.scrollTop = res[1].height - res[0].height;
					}
				});
			},
			loadMoreMessages() {
				// TODO: 实现加载历史消息的逻辑
				// console.log('加载更多消息');
			},
			handleFocus() {
				this.$nextTick(() => {
					this.scrollToBottom();
				});
			},
			handleBlur() {
				// 处理输入框失去焦点的逻辑
			},
			toggleVoiceInput() {
				// 实现语音输入的逻辑
				// console.log('切换到语音输入');

			}
		}
	}
</script>

<style>
	/* #ifdef MP-WEIXIN */
	::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
		color: transparent;
	}

	::v-deep ::-webkit-scrollbar {
		/* 滚动条整体样式 */
		display: block !important;
		width: 7rpx;
	}

	::v-deep ::-webkit-scrollbar-thumb {
		/* 滚动条里面小方块 */
		border-radius: 5rpx !important;
		box-shadow: inset 0 0 1rpx rgba(0, 0, 0, 0.2) !important;
		background-color: #CCCCCC !important;
	}

	/* #endif */
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.nav-bar {

		background: rgba(255, 255, 255, 0.98);
		backdrop-filter: blur(10px);
		border-bottom: 1px solid rgba(0, 0, 0, 0.05);
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: fixed;
		top: 0;
		width: 100%;
	}

	.nav-left {
		margin: 20rpx 30rpx;
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.model-name {
		font-size: 32rpx;
		font-weight: 500;
	}

	.model-status {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
	}

	.model-status.online {
		background-color: #3dc07c;
	}

	.nav-right {
		margin: 20rpx 30rpx;
		display: flex;
		gap: 16rpx;
	}

	.function-btn {
		background: none;
		border: none;
		padding: 16rpx;
		margin: 0;
		line-height: 1;
	}

	.chat-content {
		flex: 1;
		padding: 20rpx 0;
		overflow-y: auto;
		width: 95%;
		margin-left: 2.5%;
		margin-top: 110rpx;


	}

	.welcome-card {
		background: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		margin: 20rpx 0;
		text-align: center;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.ai-avatar {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 20rpx;
	}

	.welcome-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 16rpx;
		display: block;
	}

	.welcome-desc {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 40rpx;
		display: block;
		overflow: hidden;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
		text-overflow: ellipsis;
	}

	.suggestion-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		justify-content: center;
	}

	.suggestion-item {
		background: rgba(61, 192, 124, 0.1);
		padding: 16rpx 24rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		color: #3dc07c;
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.message-list {
		display: flex;
		flex-direction: column;
		gap: 30rpx;
	}

	.message-item {
		display: flex;
		gap: 20rpx;
		max-width: 90%;
	}

	.message-right {
		flex-direction: row-reverse;
		align-self: flex-end;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.message-content {
		display: flex;
		flex-direction: column;
	}

	.message-text {
		padding: 24rpx 28rpx;
		border-radius: 24rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		user-select: text;
		background: #ffffff;
	}

	.user-text {
		background: #3dc07c;
		color: #fff;
		box-shadow: 0 2rpx 8rpx rgba(61, 192, 124, 0.2);
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
		align-self: flex-end;
	}

	.loading-wrapper {
		display: flex;
		justify-content: center;
		margin: 20rpx 0;
	}

	.typing-indicator {
		display: flex;
		gap: 8rpx;
	}

	.dot {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background: #3dc07c;
		animation: typing 1s infinite ease-in-out;
	}

	.dot:nth-child(1) {
		animation-delay: 0.2s;
	}

	.dot:nth-child(2) {
		animation-delay: 0.3s;
	}

	.dot:nth-child(3) {
		animation-delay: 0.4s;
	}

	@keyframes typing {

		0%,
		100% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-10rpx);
		}
	}

	.input-area {
		padding: 20rpx;
		background: #fff;
		border-top: 1rpx solid #eee;
	}

	.input-wrapper {
		display: flex;
		align-items: flex-end;
		gap: 20rpx;
		background: #fff;
		border: 1px solid rgba(0, 0, 0, 0.08);
		border-radius: 36rpx;
		padding: 20rpx;
	}

	.input-box {
		flex: 1;
		min-height: 60rpx;
		/* height: 72rpx; */
		max-height: 100rpx;
		font-size: 28rpx;
		line-height: 1.5;
		background: transparent;
	}

	.send-btn {
		padding: 10rpx;
		opacity: 0.6;
		transition: all 0.3s;
	}

	.send-btn.active {
		opacity: 1;
	}
	.send-btn.disabled {
  opacity: 0.4 !important;
  pointer-events: none;
}

.send-btn.disabled uni-icons {
  color: #999 !important;
}
</style>